#!usr/bin/env python  
# -*- coding:utf-8 _*-
""" 
@author:robot
@file: tmf_ws.py 
@version:
@time: 2022/03/01 
"""
import websockets
import asyncio
import json
from TapClientCore.T03_api_body_templates.v2_api_body import DATASOURCE_WS_CUSTOMER_TEST
# from TapClientCore.T03_api_body_templates.v2_api_body import DATASOURCE_WS_KAFKA_TEST
from TapException.TM import LoadSchemaError
from TapClientCore.T02_tm_api.v2_api.v2_tm import v2tm


def build_load_schema_body(conf):
    customer_template = DATASOURCE_WS_CUSTOMER_TEST.copy()
    data = None
    ws_body = {'type': 'testConnection'}
    customer_template.update(conf)
    ws_body.update({'data': customer_template})
    return ws_body


async def load_schema(ws_uri, ws_body):
    async with websockets.connect(ws_uri) as ws:
        await ws.send(json.dumps(ws_body))
        while True:
            response = json.loads(await ws.recv())
            if response is None:
                continue
            if response.get('data').get('result').get('status') is None:
                continue
            if response.get('data').get('result').get('status') != "ready":
                raise LoadSchemaError
            for i in response.get('data').get('result').get('response_body').get('validate_details'):
                if i.get('fail_message') is not None:
                    return LoadSchemaError
            await ws.close()


def ws_load_schema(ws_uri, payload):
    ws_body = build_load_schema_body(payload)

    try:
        asyncio.get_event_loop().run_until_complete(load_schema(ws_uri, ws_body))
    except Exception as e:
        assert str(e) == "code = 1000 (OK), no reason"
    return True
